<template>
	<view class="batch-upload-page">
		<view v-if="showDraftToast" class="draft-toast">已暂存至云端草稿箱</view>

		<!-- 已添加商品预览滚动区 -->
		<view class="preview-scroll-container">
			<view class="batch-operate-bar">
				<view class="select-all">
					<checkbox v-model="selectAll" @change="handleSelectAll" :disabled="products.length === 0 || allOnShelf" />
					<text class="select-all-text">全选</text>
				</view>
				<text class="selected-count">已选{{ selectedCount }}个（{{ onShelfCount }}个已上架）</text>
			</view>

			<scroll-view class="product-preview-scroll" scroll-x show-scrollbar :scroll-into-view="viewId">
				<view class="product-preview-list">
					<view
						v-for="(product, index) in products"
						:key="product.productId"
						class="product-preview-card"
						:class="getProductCardClass(index, product)"
						@click="editProduct(index)"
						:id="'product-' + product.productId"
					>
						<view v-if="product.isOnShelf" class="on-shelf-tag">已上架</view>
						<checkbox class="product-checkbox" v-model="product.isSelected" @change="handleProductSelect(index)" :disabled="product.isOnShelf" />

						<view class="preview-image-container">
							<image :src="getProductImage(product)" mode="cover" class="preview-image"></image>
							<view class="remove-product-btn" @click.stop="removeProduct(index)" :disabled="product.isOnShelf">
								<uni-icons type="trash-filled" size="24" color="#fff"></uni-icons>
							</view>
						</view>
						<text class="preview-name">{{ product.productName || '未命名商品' }}</text>
						<text class="preview-price">¥{{ (product.price || 0).toFixed(2) }}</text>
					</view>

					<view @click="addNewProduct" class="add-product-btn">
						<uni-icons type="plusempty" size="20"></uni-icons>
						<text>添加商品</text>
					</view>
				</view>
			</scroll-view>

			<view class="">
				<view
					class="submit-btn"
					:class="{ disabled: isSubmitting || selectedCount === 0 || allSelectedOnShelf }"
					:disabled="isSubmitting || selectedCount === 0 || allSelectedOnShelf"
				>
					<view class="" v-if="!isSubmitting" @click="submitSelectedProducts">
						<view class=""><text>批量上架</text></view>
						<view class="">
							<text style="font-size: 24rpx; color: #ccc">选中{{ selectedCount }}个，可上架{{ selectedCount - selectedOnShelfCount }}个</text>
						</view>
					</view>
					<view class=""><text v-if="isSubmitting">提交中...</text></view>
				</view>
			</view>
		</view>

		<!-- 商品编辑区域 -->
		<view class="edit-container">
			<view v-if="currentProduct.isOnShelf" class="edit-on-shelf-hint">
				<uni-icons type="info" size="20" color="#ff9f43"></uni-icons>
				<text>已上架商品编辑后需重新提交上架</text>
			</view>

			<form @submit="saveCurrentProduct" class="form-container">
				<!-- 商品名称 -->
				<view class="form-item">
					<view class="form-label">
						<text>商品名称</text>
						<text class="required">*</text>
					</view>
					<input type="text" v-model="currentProduct.productName" placeholder="请输入商品名称" class="form-input" maxlength="50" />
				</view>

				<!-- 商品图片（暂存时上传云端） -->
				<view class="form-item">
					<view class="form-label">
						<text>商品图片</text>
						<text class="required">*</text>
					</view>
					<view class="image-upload-container">
						<view v-for="(image, idx) in currentProduct.images" :key="idx" class="image-item">
							<image :src="image.url || placeholderImage" mode="cover" class="uploaded-image"></image>
							<button @click.stop="removeImage(idx)" class="image-remove-btn">
								<uni-icons type="trash" size="20" color="#fff"></uni-icons>
							</button>
						</view>
						<button v-if="currentProduct.images.length < 9" @click.stop="chooseAndUploadImage" class="add-image-btn">
							<uni-icons type="plusempty" size="20"></uni-icons>
							<text class="add-image-text">添加图片</text>
						</button>
						<text class="image-count-hint">最多9张（暂存时自动上传云端）</text>
					</view>
				</view>

				<!-- 单位、单价、库存 -->
				<view class="form-item">
					<view class="form-label">
						<text>基本信息</text>
						<text class="required">*</text>
					</view>
					<view class="info-grid">
						<view class="info-item">
							<text>单位：</text>
							<text class="required">*</text>
							<input type="text" v-model="currentProduct.unit" placeholder="个/件/套" class="form-input" maxlength="4" />
						</view>
						<view class="info-item">
							<text>单价：</text>
							<text class="required">*</text>
							<input type="number" v-model="currentProduct.price" placeholder="0.00" class="form-input" step="0.01" min="0" />
							<text class="price-unit">元</text>
						</view>
						<view class="info-item">
							<text>原价：</text>
							<text style="font-size: 24rpx">(不填，默认为售价)</text>
							<input type="number" v-model="currentProduct.originalPrice" placeholder="0.00" class="form-input" step="0.01" min="0" />
							<text class="price-unit">元</text>
						</view>
						<view class="info-item">
							<text>库存：</text>
							<text style="font-size: 24rpx">(不填，默认为不控制)</text>
							<input type="number" v-model="currentProduct.stock" placeholder="0" class="form-input" min="0" />
							<text class="stock-unit">{{ currentProduct.unit || '件' }}</text>
						</view>
					</view>
				</view>

				<!-- 商品详情、有效期、销售区域 -->
				<view class="form-item">
					<view class="form-label">
						<text>商品详情描述</text>
					</view>
					<textarea v-model="currentProduct.description" placeholder="请输入商品详情(100字以内)..." class="form-textarea" maxlength="100"></textarea>
					<text class="textarea-count">{{ currentProduct.description.length }}/100</text>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text>上架有效期间</text>
						<text class="required">*</text>
					</view>
					<view class="date-range">
						<view class="date-item">
							<text class="date-label">开始日期</text>
							<picker mode="date" :value="currentProduct.startDate" start="2023-01-01" @change="onStartDateChange" class="date-picker">
								<view class="picker-view">
									<text>{{ currentProduct.startDate || '选择日期' }}</text>
									<uni-icons type="calendar" size="20"></uni-icons>
								</view>
							</picker>
						</view>
						<view class="date-separator">至</view>
						<view class="date-item">
							<text class="date-label">结束日期</text>
							<picker mode="date" :value="currentProduct.endDate" :start="currentProduct.startDate || '2023-01-01'" @change="onEndDateChange" class="date-picker">
								<view class="picker-view">
									<text>{{ currentProduct.endDate || '选择日期' }}</text>
									<uni-icons type="calendar" size="20"></uni-icons>
								</view>
							</picker>
						</view>
					</view>
				</view>
				<view class="form-item">
					<view class="form-label">
						<text>选择销售区域</text>
						<text class="required">*</text>
					</view>
					<input type="text" v-model="currentProduct.saleArea" placeholder="请选择销售区域" class="form-input" readonly />
				</view>

				<!-- 暂存按钮 -->
				<button type="primary" size="mini" form-type="submit" class="save-product-btn" :disabled="isSubmitting || currentProduct.isOnShelf">
					{{ currentProduct.isOnShelf ? '已上架，编辑后需重新提交' : '暂存至云端' }}
				</button>
			</form>
		</view>
	</view>
</template>

<script>
const db = uniCloud.databaseForJQL();
import { productMsg } from '../../methods/msgSend';
export default {
	data() {
		return {
			toTarget: null,
			isSubmitting: false,
			showDraftToast: false,
			placeholderImage: '/static/images/product-placeholder.png',
			products: [], // 商品列表（存储云端图片信息：{url: '', fileID: ''}）
			currentEditIndex: -1,
			currentProduct: {
				productId: '',
				productName: '',
				images: [], // 格式：[{ url: '云端临时URL', fileID: '云端文件ID' }, ...]
				unit: '',
				price: 0,
				stock: 0,
				originalPrice: 0,
				description: '',
				startDate: '',
				endDate: '',
				saleArea: '',
				isOnShelf: false,
				isSelected: false
			},
			viewId: '',
			selectAll: false,
			draftId: '' // 云端草稿唯一ID（用于更新草稿）
		};
	},
	computed: {
		storeData() {
			return this.$store.state.msg || { user: { userId: 'default-user' } };
		},
		selectedCount() {
			console.log('this',this.products);
			return this.products.filter(p => p.isSelected).length;
		},
		onShelfCount() {
			return this.products.filter(p => p.isOnShelf).length;
		},
		selectedOnShelfCount() {
			return this.products.filter(p => p.isSelected && p.isOnShelf).length;
		},
		allSelectedOnShelf() {
			return this.selectedCount > 0 && this.selectedCount === this.selectedOnShelfCount;
		},
		allOnShelf() {
			return this.products.length > 0 && this.products.every(p => p.isOnShelf);
		}
	},
	watch: {
		products: {
			deep: true,
			handler(newVal) {
				if (newVal.length === 0) {
					this.selectAll = false;
					return;
				}
				const unShelfProducts = newVal.filter(p => !p.isOnShelf);
				this.selectAll = unShelfProducts.every(p => p.isSelected) && unShelfProducts.length > 0;

				if (newVal.length > 0) {
					this.$nextTick(() => {
						const lastProduct = newVal[newVal.length - 1];
						this.viewId = 'product-' + lastProduct.productId;
					});
				}
			}
		}
	},
	onLoad(res) {
		this.toTarget = res.toTarget ? JSON.parse(decodeURIComponent(res.toTarget)) : {};
		this.initDefaultDate();
		this.loadCloudDraft(); // 加载云端草稿
	},
	methods: {
		// 获取商品卡片的样式类
		getProductCardClass(index, product) {
			return {
				'active': this.currentEditIndex === index,
				'on-shelf': product.isOnShelf
			};
		},
		
		// 获取商品图片地址
		getProductImage(product) {
			if (product.images && product.images.length > 0 && product.images[0].url) {
				return product.images[0].url;
			}
			return this.placeholderImage;
		},
		
		initDefaultDate() {
			const today = this.formatDate(new Date());
			const endDate = new Date();
			endDate.setDate(endDate.getDate() + 30);
			this.currentProduct.startDate = today;
			this.currentProduct.endDate = this.formatDate(endDate);
		},
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return year + '-' + month + '-' + day;
		},
		navigateBack() {
			this.saveCloudDraft(); // 返回时保存到云端
			uni.navigateBack();
		},

		// 选择图片并立即上传云端
		async chooseAndUploadImage() {
			const maxCount = 9 - this.currentProduct.images.length;
			if (maxCount <= 0) {
				uni.showToast({ title: '最多上传9张图片', icon: 'none' });
				return;
			}

			// 选择图片
			const chooseRes = await new Promise((resolve, reject) => {
				uni.chooseImage({
					count: maxCount,
					sizeType: ['compressed'], // 压缩图片，减少上传时间
					sourceType: ['album', 'camera'],
					success: resolve,
					fail: reject
				});
			});

			// 过滤大图片
			const validFiles = chooseRes.tempFiles.filter(file => file.size <= 5 * 1024 * 1024);
			if (validFiles.length < chooseRes.tempFiles.length) {
				uni.showToast({ title: '部分图片超过5MB，已过滤', icon: 'none' });
			}

			// 上传图片到云端（并行上传）
			uni.showLoading({ title: '图片上传中...' });
			try {
				const uploadPromises = validFiles.map(file => this.uploadImageToCloud(file.path));
				const cloudImages = await Promise.all(uploadPromises);
				// 保存云端图片信息（含URL和fileID）
				this.currentProduct.images = [...this.currentProduct.images, ...cloudImages];
			} catch (e) {
				console.error('图片上传失败:', e);
				uni.showToast({ title: '图片上传失败，请重试', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 上传图片到uniCloud
		uploadImageToCloud(tempFilePath) {
			return new Promise((resolve, reject) => {
				const ext = tempFilePath.split('.').pop().toLowerCase();
				const fileName = 'product/drafts/' + this.storeData.user.userId + '/' + Date.now() + '-' + Math.random().toString(36).slice(2, 10) + '.' + ext;
				const cloudPath = fileName;

				uniCloud.uploadFile({
					cloudPath,
					filePath: tempFilePath,
					success: async (uploadRes) => {
						if (!uploadRes.fileID) {
							reject(new Error('未获取到云端文件ID'));
							return;
						}
						// 获取临时访问URL（有效期2小时，加载时会刷新）
						const tempRes = await uniCloud.getTempFileURL({ fileList: [uploadRes.fileID] });
						const imageUrl = tempRes.fileList[0]?.tempFileURL;
						if (imageUrl) {
							// 返回云端图片信息（URL用于显示，fileID用于后续加载/提交）
							resolve({
								url: imageUrl,
								fileID: uploadRes.fileID
							});
						} else {
							reject(new Error('获取图片URL失败'));
						}
					},
					fail: (e) => {
						reject(new Error('上传失败：' + e.errMsg));
					}
				});
			});
		},

		// 加载云端草稿
		async loadCloudDraft() {
			uni.showLoading({ title: '加载云端草稿...' });
			try {
				// 查询当前用户的草稿（userId唯一，确保数据隔离）
				const res = await db
					.collection('drafts')
					.where({ userId: this.storeData.user.userId })
					.orderBy('updateTime', 'desc')
					.get();

				if (res.data.length > 0) {
					const draft = res.data[0];
					this.draftId = draft._id; // 记录草稿ID，用于后续更新
					// 刷新图片URL（临时URL可能过期，通过fileID重新获取）
					this.products = await this.refreshDraftImages(draft.products);

					// 询问用户是否加载
					uni.showModal({
						title: '检测到云端草稿',
						content: '是否加载上次未完成的' + this.products.length + '个商品信息？',
						success: (modalRes) => {
							if (!modalRes.confirm) {
								this.clearCloudDraft(); // 清空草稿
							} else if (this.products.length > 0) {
								this.editProduct(0); // 编辑第一个商品
							}
						}
					});
				} else {
					// 无草稿，初始化空列表
					this.products = [];
				}
			} catch (e) {
				console.error('加载云端草稿失败:', e);
				uni.showToast({ title: '草稿加载失败，将创建新草稿', icon: 'none' });
				this.products = [];
			} finally {
				uni.hideLoading();
			}
		},

		// 刷新草稿图片URL（解决临时URL过期问题）
		async refreshDraftImages(products) {
			if (!products || products.length === 0) return [];

			// 收集所有商品的fileID（去重，减少请求次数）
			const allFileIDs = [];
			products.forEach(product => {
				product.images.forEach(img => {
					if (img.fileID && !allFileIDs.includes(img.fileID)) {
						allFileIDs.push(img.fileID);
					}
				});
			});

			// 批量获取最新临时URL
			const tempRes = await uniCloud.getTempFileURL({ fileList: allFileIDs });
			const fileIDToUrl = {};
			tempRes.fileList.forEach(item => {
				if (item.tempFileURL) {
					fileIDToUrl[item.fileID] = item.tempFileURL;
				}
			});

			// 替换图片URL为最新值
			return products.map(product => ({
				...product,
				images: product.images.map(img => ({
					...img,
					url: fileIDToUrl[img.fileID] || this.placeholderImage // 兜底占位图
				}))
			}));
		},

		// 保存草稿到云端
		async saveCloudDraft() {
			if (this.products.length === 0) {
				// 空列表，删除现有草稿
				if (this.draftId) {
					await db.collection('drafts').doc(this.draftId).remove();
					this.draftId = '';
				}
				return;
			}

			uni.showLoading({ title: '保存至云端...' });
			try {
				const draftData = {
					userId: this.storeData.user.userId,
					products: this.products,
					updateTime: Date.now() // 服务器时间，确保准确性
				};

				if (this.draftId) {
					// 已有草稿，更新
					await db.collection('drafts').doc(this.draftId).update(draftData);
				} else {
					// 新草稿，新增
					const addRes = await db.collection('drafts').add(draftData);
					this.draftId = addRes.id; // 记录新草稿ID
				}

				this.showDraftToast = true;
				setTimeout(() => this.showDraftToast = false, 2000);
			} catch (e) {
				console.error('保存云端草稿失败:', e);
				uni.showToast({ title: '草稿保存失败，请重试', icon: 'none' });
			} finally {
				uni.hideLoading();
			}
		},

		// 清空云端草稿
		async clearCloudDraft() {
			try {
				if (this.draftId) {
					// 删除草稿记录
					await db.collection('drafts').doc(this.draftId).remove();
				}
				this.products = [];
				this.currentEditIndex = -1;
				this.initDefaultDate();
				this.draftId = '';
			} catch (e) {
				console.error('清空草稿失败:', e);
				uni.showToast({ title: '清空草稿失败', icon: 'none' });
			}
		},

		addNewProduct() {
			if (this.currentEditIndex !== -1) {
				this.saveCurrentProduct();
			}

			const today = this.formatDate(new Date());
			const endDate = new Date();
			endDate.setDate(endDate.getDate() + 30);
			const productId = this.storeData.user.userId + '-' + Date.now();
			const newProduct = {
				productId,
				productName: '',
				images: [], // 空数组，后续通过上传填充云端信息
				unit: '',
				price: 0,
				stock: 0,
				originalPrice: 0,
				description: '',
				startDate: today,
				endDate: this.formatDate(endDate),
				saleArea: '',
				isOnShelf: false,
				isSelected: false
			};

			this.products.push(newProduct);
			this.editProduct(this.products.length - 1);
		},

		editProduct(index) {
			if (this.currentEditIndex !== -1 && this.currentEditIndex !== index) {
				this.saveCurrentProduct();
			}

			const product = this.products[index];
			this.currentEditIndex = index;
			// 深拷贝，避免直接修改原数组（图片信息含URL和fileID）
			this.currentProduct = JSON.parse(JSON.stringify(product));

			if (product.isOnShelf) {
				uni.showToast({ title: '已上架商品编辑后需重新提交', icon: 'none', duration: 1500 });
			}
		},

		removeProduct(index) {
			const product = this.products[index];
			if (product.isOnShelf) {
				uni.showToast({ title: '已上架商品无法删除', icon: 'none' });
				return;
			}

			uni.showModal({
				title: '提示',
				content: '确定要删除这个商品吗？（将同时删除云端图片）',
				success: async (res) => {
					if (res.confirm) {
						// 删除该商品的云端图片
						const fileIDs = product.images.map(img => img.fileID).filter(Boolean);
						if (fileIDs.length > 0) {
							await uniCloud.deleteFile({ fileList: fileIDs }).catch(e => {
								console.error('删除商品图片失败:', e);
							});
						}

						this.products.splice(index, 1);
						if (this.currentEditIndex === index) {
							if (this.products.length > 0) {
								this.editProduct(0);
							} else {
								this.currentEditIndex = -1;
								this.initDefaultDate();
							}
						} else if (this.currentEditIndex > index) {
							this.currentEditIndex--;
						}

						this.saveCloudDraft(); // 同步删除到云端
					}
				}
			});
		},

		removeImage(idx) {
			// 记录要删除的图片fileID
			const fileID = this.currentProduct.images[idx].fileID;
			// 从本地列表移除
			this.currentProduct.images.splice(idx, 1);
			// 立即删除云端图片
			if (fileID) {
				uniCloud.deleteFile({ fileList: [fileID] }).catch(e => {
					console.error('删除单张图片失败:', e);
				});
			}
		},

		onStartDateChange(e) {
			this.currentProduct.startDate = e.detail.value;
			if (this.currentProduct.endDate && this.currentProduct.endDate < this.currentProduct.startDate) {
				this.currentProduct.endDate = this.currentProduct.startDate;
			}
		},

		onEndDateChange(e) {
			this.currentProduct.endDate = e.detail.value;
		},

		validateProduct(product) {
			if (!product.productName?.trim()) {
				uni.showToast({ title: '请输入商品名称', icon: 'none' });
				return false;
			}
			if (product.images.length === 0) {
				uni.showToast({ title: '请至少上传一张商品图片', icon: 'none' });
				return false;
			}
			if (!product.unit?.trim()) {
				uni.showToast({ title: '请输入商品单位', icon: 'none' });
				return false;
			}
			if (isNaN(Number(product.price)) || Number(product.price) <= 0) {
				uni.showToast({ title: '请输入有效的商品单价', icon: 'none' });
				return false;
			}
			if (!product.startDate || !product.endDate) {
				uni.showToast({ title: '请选择上架有效期间', icon: 'none' });
				return false;
			}
			if (!product.saleArea?.trim()) {
				uni.showToast({ title: '请选择销售区域', icon: 'none' });
				return false;
			}
			return true;
		},

		async saveCurrentProduct(e) {
			if (e) e.preventDefault();
			if (this.isSubmitting) return;
			if (this.currentEditIndex === -1) {
				uni.showToast({ title: '请选择要编辑的商品', icon: 'none' });
				return;
			}

			// 格式化数值
			this.currentProduct.price = Number(this.currentProduct.price) || 0;
			this.currentProduct.stock = Number(this.currentProduct.stock) || 0;
			this.currentProduct.originalPrice = Number(this.currentProduct.originalPrice) || this.currentProduct.price;

			if (!this.validateProduct(this.currentProduct)) {
				return;
			}

			this.isSubmitting = true;
			// 编辑已上架商品，取消上架状态
			const updatedProduct = {
				...this.currentProduct,
				isOnShelf: false,
				isSelected: false
			};

			this.products[this.currentEditIndex] = updatedProduct;
			await this.saveCloudDraft(); // 保存到云端
			uni.showToast({ title: '商品信息已同步至云端', icon: 'success', duration: 1000 });
			this.isSubmitting = false;
		},

		handleProductSelect(index) {
			console.log('77777',product.isOnShelf);
			const product = this.products[index];
			if (product.isOnShelf) return;
			this.products[index].isSelected = !product.isSelected;
			console.log('8888',this.products[index].isSelected );
		},

		handleSelectAll() {
			if (this.allOnShelf) return;
			const isSelect = !this.selectAll;
			this.products.forEach(product => {
				if (!product.isOnShelf) {
					product.isSelected = isSelect;
				}
			});
		},

		async submitSelectedProducts() {
			const toSubmitProducts = this.products.filter(p => !p.isOnShelf && p.isSelected);
			if (toSubmitProducts.length === 0) {
				uni.showToast({ title: '请选择待上架商品', icon: 'none' });
				return;
			}

			// 验证商品
			for (const product of toSubmitProducts) {
				if (!this.validateProduct(product)) {
					const index = this.products.findIndex(p => p.productId === product.productId);
					this.editProduct(index);
					return;
				}
			}

			this.isSubmitting = true;
			try {
				// 提交时无需重新上传图片（已在暂存时上传，直接用fileID）
				const processedProducts = toSubmitProducts.map(product => ({
					...product,
					originalPrice: product.originalPrice === 0 ? product.price : Number(product.originalPrice),
					senderUserId: this.storeData.user.userId,
					// 提交时可仅传fileID，也可传URL（根据后端需求）
					images: product.images.map(img => ({ url: img.url, fileID: img.fileID })),
					createTime: db.serverDate()
				}));

				// 提交到商品集合
				const res = await db.collection('sendgood').add(processedProducts);
				if (res.inserted > 0) {
					// 更新上架状态
					this.products.forEach(product => {
						if (toSubmitProducts.some(p => p.productId === product.productId)) {
							product.isOnShelf = true;
							product.isSelected = false;
						}
					});

					// 发送通知
					await productMsg(this.toTarget, res.ids, this.storeData);
					// 提交后更新云端草稿（标记上架状态）
					await this.saveCloudDraft();

					uni.showToast({ title: '成功上架' + res.inserted + '个商品', icon: 'success' });
					setTimeout(() => {
						uni.redirectTo({ url: '/pages/main/main' });
					}, 1500);
				}
			} catch (error) {
				console.error('商品上架失败:', error);
				uni.showToast({ title: '上架失败，请重试', icon: 'none' });
			} finally {
				this.isSubmitting = false;
			}
		}
	}
};
</script>

<style scoped lang="scss">
$primary-color: #165dff;
$primary-light: #e8f3ff;
$text-primary: #1d2129;
$text-secondary: #4e5969;
$text-placeholder: #86909c;
$border-color: #e5e6eb;
$red-color: #f53f3f;
$green-color: #00b42a;
$gray-bg: #f5f7fa;
$white: #ffffff;
$radius: 6px;
$spacing-sm: 8px;
$spacing-md: 16px;
$spacing-lg: 24px;

.batch-upload-page {
	background-color: $gray-bg;
	min-height: 100vh;
	padding-top: 10rpx;
}

.batch-operate-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 8rpx 16rpx;
	margin-bottom: 12rpx;
	font-size: 24rpx;
	color: $text-secondary;

	.select-all {
		display: flex;
		align-items: center;
		gap: 8rpx;

		.select-all-text {
			color: $text-primary;
		}
	}

	.selected-count {
		font-size: 22rpx;
	}
}

.preview-scroll-container {
	background-color: $white;
	border-bottom: 1px solid $border-color;
	padding: 12px 16px;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 9999;
	max-height: 50vh;
	overflow-y: auto;

	.product-preview-scroll {
		width: 100%;
		white-space: nowrap;
		padding-bottom: 8px;
	}

	.product-preview-list {
		display: inline-flex;
		gap: 12px;
	}

	.product-preview-card {
		width: 140px;
		display: inline-flex;
		flex-direction: column;
		background-color: $white;
		border-radius: $radius;
		border: 1px solid $border-color;
		padding: 10px;
		transition: all 0.2s;
		white-space: normal;
		position: relative;

		&.on-shelf {
			border-color: $green-color;
			opacity: 0.9;
		}

		&.active {
			border-color: $primary-color;
			box-shadow: 0 0 0 2px $primary-light;
		}

		.on-shelf-tag {
			position: absolute;
			top: 8rpx;
			left: 8rpx;
			background-color: $green-color;
			color: $white;
			font-size: 20rpx;
			padding: 2rpx 8rpx;
			border-radius: 4rpx;
			z-index: 10;
		}

		.product-checkbox {
			position: absolute;
			top: 8rpx;
			right: 8rpx;
			z-index: 10;
			transform: scale(0.8);
		}

		.preview-image-container {
			position: relative;
			width: 100%;
			aspect-ratio: 1/1;
			border-radius: 4px;
			overflow: hidden;
			margin-bottom: 8px;
			background-color: #f9f9f9;

			.preview-image {
				width: 100%;
				height: 100%;
				object-fit: cover;
			}

			.remove-product-btn {
				position: absolute;
				top: 0;
				left: 0;
				width: 24px;
				height: 24px;
				background-color: rgba(0, 0, 0, 0.4);
				display: flex;
				align-items: center;
				justify-content: center;
				padding: 0;
				color: $white;
				border-radius: 50%;
				font-size: 14px;
				z-index: 10;

				&[disabled] {
					opacity: 0.5;
					cursor: not-allowed;
				}
			}
		}

		.preview-name {
			font-size: 13px;
			color: $text-primary;
			line-height: 1.3;
			height: 28px;
			overflow: hidden;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			-webkit-box-orient: vertical;
			margin-bottom: 4px;
		}

		.preview-price {
			font-size: 14px;
			color: $red-color;
			font-weight: 500;
		}
	}

	.add-product-btn {
		width: 140px;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: $white;
		border: 1px dashed $border-color;
		border-radius: $radius;
		color: $text-placeholder;
		transition: all 0.2s;

		&:hover {
			border-color: $primary-color;
			color: $primary-color;
		}

		uni-icons {
			font-size: 24px;
			margin-bottom: 8px;
		}

		text {
			font-size: 13px;
		}
	}
}

.edit-container {
	padding: $spacing-md;
	background-color: $gray-bg;
	margin-top: 600rpx;
}

.edit-on-shelf-hint {
	display: flex;
	align-items: center;
	gap: 8rpx;
	padding: 12rpx 16rpx;
	background-color: #fff8e6;
	border-left: 4rpx solid #ff9f43;
	margin-bottom: 24rpx;
	font-size: 24rpx;
	color: #ff7d00;
}

.form-container {
	background-color: $white;
	border-radius: $radius;
	padding: $spacing-md;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.form-item {
	margin-bottom: $spacing-lg;

	.form-label {
		display: flex;
		align-items: center;
		margin-bottom: $spacing-sm;
		font-size: 14px;
		font-weight: 500;
		color: $text-primary;

		.required {
			color: $red-color;
			margin-left: 4px;
		}
	}

	.form-input {
		width: 100%;
		padding: 12px 16px;
		border: 1px solid $border-color;
		border-radius: $radius;
		font-size: 14px;
		color: $text-primary;
		background-color: $white;

		&::placeholder {
			color: $text-placeholder;
		}

		&:focus {
			outline: none;
			border-color: $primary-color;
			box-shadow: 0 0 0 2px $primary-light;
		}

		&[readonly] {
			background-color: #fafafa;
			cursor: not-allowed;
		}
	}
}

.image-upload-container {
	position: relative;
	display: grid;
	grid-template-columns: repeat(4, 1fr);
	gap: 12px;

	.image-item {
		position: relative;
		width: 100%;
		aspect-ratio: 1/1;
		border-radius: $radius;
		overflow: hidden;
		background-color: $white;

		.uploaded-image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.image-remove-btn {
			position: absolute;
			top: 4px;
			right: 4px;
			width: 24px;
			height: 24px;
			display: flex;
			align-items: center;
			justify-content: center;
			padding: 0;
			background-color: rgba(0, 0, 0, 0.5);
			color: white;
			border-radius: 50%;
			font-size: 14px;
			z-index: 999;
		}
	}

	.add-image-btn {
		width: 100%;
		aspect-ratio: 1/1;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		background-color: $white;
		border: 2px dashed $border-color;
		border-radius: $radius;
		color: $text-placeholder;

		.add-image-text {
			font-size: 12px;
			margin-top: 8rpx;
		}
	}

	.image-count-hint {
		position: absolute;
		right: 0;
		top: -20px;
		font-size: 12px;
		color: $text-placeholder;
	}
}

.info-grid {
	display: flex;
	flex-direction: column;
	gap: 12px;

	.info-item {
		position: relative;

		.form-input {
			padding-right: 30px;
		}

		.price-unit,
		.stock-unit {
			position: absolute;
			right: 16px;
			top: 50%;
			transform: translateY(-50%);
			font-size: 14px;
			color: $text-placeholder;
		}
	}
}

.form-textarea {
	width: 100%;
	min-height: 60px;
	max-height: 120px;
	padding: 12px 16px;
	border: 1px solid $border-color;
	border-radius: $radius;
	font-size: 14px;
	color: $text-primary;
	background-color: $white;
	resize: vertical;

	&::placeholder {
		color: $text-placeholder;
	}

	&:focus {
		outline: none;
		border-color: $primary-color;
		box-shadow: 0 0 0 2px $primary-light;
	}
}

.textarea-count {
	display: flex;
	justify-content: flex-end;
	margin-top: 8px;
	font-size: 12px;
	color: $text-placeholder;
}

.date-range {
	display: flex;
	align-items: center;
	gap: 12px;

	.date-item {
		flex: 1;

		.date-label {
			display: block;
			margin-bottom: 8px;
			font-size: 12px;
			color: $text-secondary;
		}

		.date-picker {
			width: 100%;
		}

		.picker-view {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 12px 16px;
			border: 1px solid $border-color;
			border-radius: $radius;
			background-color: $white;
			font-size: 14px;
			color: $text-primary;

			uni-icons {
				color: $text-placeholder;
			}
		}
	}

	.date-separator {
		color: $text-secondary;
		font-size: 16px;
		padding: 0 4px;
	}
}

.save-product-btn {
	width: 100%;
	padding: 14px 0;
	background-color: $primary-color;
	color: $white;
	border-radius: $radius;
	font-size: 16px;
	font-weight: 500;
	margin-top: $spacing-md;

	&[disabled] {
		background-color: $text-placeholder;
		cursor: not-allowed;
	}
}

.submit-btn {
	display: flex;
	flex-direction: column;
	align-items: center;
	text-align: center;
	justify-content: center;
	padding: 10rpx 20rpx;
	background-color: $primary-color;
	color: $white;
	border-radius: $radius;
	font-size: 28rpx;
	font-weight: 500;
	transition: background-color 0.2s;
	margin: 16rpx auto;

	&.disabled {
		background-color: $text-placeholder;
		cursor: not-allowed;
	}
}

.draft-toast {
	position: fixed;
	bottom: 30px;
	left: 50%;
	transform: translateX(-50%);
	background-color: rgba(0, 0, 0, 0.7);
	color: $white;
	padding: 8px 16px;
	border-radius: 100px;
	font-size: 14px;
	z-index: 100;
	animation: fadeInOut 2s;
}

@keyframes fadeInOut {
	0% { opacity: 0; }
	20% { opacity: 1; }
	80% { opacity: 1; }
	100% { opacity: 0; }
}
</style>
